NG.database = function() {
	var DEMODB = null;
	var _instance = null;

	function initDatabase() {
		try {
		    if (!window.openDatabase) {
		        NGLogger.info('Databases are not supported in this browser.');
		    } else {
		        var shortName = 'NGDB';
		        var version = '1.0';
		        var displayName = 'NGDB Database';
		        var maxSize = 1024*1024*10; //  bytes
		        DEMODB = openDatabase(shortName, version, displayName, maxSize);
				createTables();
				NGLogger.info(shortName + " initialized.");
		    }
		} catch(e) {
		    if (e == 2) {
		        // Version number mismatch.
		        NGLogger.info("Invalid database version.");
		    } else {
		        NGLogger.info("Unknown error "+e+".");
		    }
		    return;
		}
	}
	
	function errorHandler (tx, err) {
		NGLogger.info('DbError: ' + err.message + ' (Code ' + err.code + ')');
		return false;
	};
	
	function dataHandler(tx, data) { 
		if (typeof (data) != 'undefined') {
			if (data.rows.length == 0) { 
				//TODO CHECK FOR rowsAffected,insertedId FOR updates,deletes, inserts. 
				NGLogger.info("DML sql call");
			} 
			else if (data.rows.length > 0) { //selects
				for (i = 0; i < data.rows.length; i++) {
					var row = data.rows.item(i);
					var data = [row['id'] ,row['notes'], row['date']]; //sets value in array
					//TODO CONSUME THE DATA HERE 
				} 
			}
		}
	};					

	function createTables(){
		DEMODB.transaction(
	        function (transaction) {
	        	transaction.executeSql('CREATE TABLE IF NOT EXISTS tiles(id TEXT NOT NULL PRIMARY KEY, image BLOB);', [], dataHandler, errorHandler);
	        }
	    );
		//prePopulate();
	}
	

	return {
		getInstance : function() {
			if (_instance === null) {
		        initDatabase();
				_instance = Ext.apply(new Ext.util.Observable, {
					publicProperty : "You can access this",

					publicMethod : function() {
						return "You can call this";
					},
					execute: function (sql, params, dataHandler, errHandler) {
						if (Ext.isEmpty(errHandler))
							errHandler = errorHandler;
						if (DEMODB) {//transaction is open
							DEMODB.transaction(function (tx) {
								tx.executeSql(sql, params, dataHandler, errHandler);
							});
						}
					},
					constructor: function(config){
				        this.name = config.name;
				        this.addEvents({
				            "created" : true,
				            "inserted" : true
				        });
	
				        // Copy configured listeners into *this* object so that the base class's
				        // constructor will add them.
				        this.listeners = config.listeners;
	
				        // Call our superclass constructor to complete construction process.
				        Ext.util.Observable.constructor.call(this, config);
				    }				
				});
			}
			return _instance;
		}
	};
}();